package com.heima.wemedia.interceptor;

import com.aliyuncs.utils.StringUtils;
import com.heima.common.threadlocal.UserThreadLocalUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserIdInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从header中获取userId
        String userId = request.getHeader("userId");
        if(StringUtils.isEmpty(userId)){
            return false;
        }
        // 存入ThreadLocal
        UserThreadLocalUtils.setUserId(Integer.valueOf(userId));
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理ThreadLocal
        UserThreadLocalUtils.removeUser();
    }
}
